import { CoolController, BaseController } from '@cool-midway/core';
import { TaskJobEntity } from '../../entity/job';
import { TaskAppEntity } from '../../entity/app';
import { TaskJobService } from '../../service/job';
import { Inject, Post, Body } from '@midwayjs/core';

/**
 * 任务
 */
@CoolController({
  api: ['add', 'update', 'page', 'info'],
  entity: TaskJobEntity,
  service: TaskJobService,
  pageQueryOp: {
    keyWordLikeFields: ['a.name', 'a.jobId'],
    select: ['a.*', 'b.name as appName'],
    fieldEq: [
      { requestParam: 'appId', column: 'a.appId' },
      { requestParam: 'status', column: 'a.status' },
    ],
    join: [{ entity: TaskAppEntity, alias: 'b', condition: 'b.id = a.appId' }],
    where: async ctx => {
      const { appName, name, topic } = ctx.request.body;
      return [
        ['b.name like :appName', { appName: `%${appName}%` }, appName],
        ['a.name like :name', { name: `%${name}%` }, name],
        ['a.topic like :topic', { topic: `%${topic}%` }, topic],
      ];
    },
  },
})
export class AdminTaskJobController extends BaseController {
  @Inject()
  taskJobService: TaskJobService;

  @Post('/remove', { summary: '移除' })
  async remove(@Body('id') id: number) {
    await this.taskJobService.removeById(id);
    return this.ok();
  }

  @Post('/stop', { summary: '停止' })
  async stop(@Body('id') id: number) {
    await this.taskJobService.stopById(id);
    return this.ok();
  }

  @Post('/start', { summary: '启动' })
  async start(@Body('id') id: number) {
    await this.taskJobService.startById(id);
    return this.ok();
  }
}
